package br.com.jvet.persistencia;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ejb.Stateless;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Root;

import br.com.jvet.entidade.Animal;

@Stateless
public class AnimalDAO extends AbstractDAO<Animal, Integer> {
	
	private static String SELECT_EXISTE = "SELECT a from "
			+ Animal.class.getSimpleName()
			+ " a where a.cliente =:cliente and upper(a.nomeAnimal) =:nome and a.tipoAnimal =:tipoanimal";


	public AnimalDAO() {
		super(Animal.class);
	}

	public boolean existe(Animal animal) {
		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("cliente", animal.getCliente());
		parameters.put("nome", animal.getNomeAnimal().toUpperCase()
				.trim());
		parameters.put("tipoanimal", animal.getTipoAnimal());


		Animal outro = super.buscarUmResultado(SELECT_EXISTE, parameters);
		if (outro != null && outro.getCodigo() != animal.getCodigo()) {
			return true;
		}
		return false;
	}

	public List<Animal> buscarAnimalPorParametro(Map<String, Object> parameters) {

		CriteriaBuilder cb = super.getEntityManager().getCriteriaBuilder();
		CriteriaQuery<Animal> cq = cb.createQuery(Animal.class);

		Root<Animal> root = cq.from(Animal.class);
		cq.select(root);

		if (parameters.containsKey("cliente")) {
			Path<String> name = root.get("cliente");
			cq.where(cb.and(cb.equal(name, parameters.get("cliente"))));
		}

		if (parameters.containsKey("datainicial")
				&& parameters.containsKey("datafinal")) {
			Path<Date> data = root.get("dataCadastro");
			cq.where(cb.between(data, (Date) parameters.get("datainicial"),
					(Date) parameters.get("datafinal")));
		}

		TypedQuery<Animal> query = super.getEntityManager().createQuery(cq);

		return query.getResultList();

	}
}
